<template>
  <div class="balance-page">
    <Header :scroll="scroll" />

    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">我的钱包</h1>
        <p class="page-subtitle">管理您的账户余额和交易记录</p>
      </div>
    </div>

    <!-- 余额概览区域 -->
    <div class="balance-overview">
      <div class="container">
        <!-- 主要余额卡片 -->
        <div class="main-balance-card">
          <div class="balance-header">
            <div class="balance-icon">
              <div class="icon-wrapper">
                <span class="wallet-icon">💰</span>
              </div>
            </div>
            <div class="balance-actions">
              <button class="action-btn recharge-btn" @click="recharge">
                <span class="btn-icon">+</span>
                充值
              </button>
              <button class="action-btn withdraw-btn" @click="withdraw">
                <span class="btn-icon">-</span>
                提现
              </button>
            </div>
          </div>
          <div class="balance-content">
            <div class="total-balance">
              <span class="balance-label">账户余额</span>
              <div class="balance-amount">
                <span class="currency">¥</span>
                <span class="amount">{{ userBalance.totalBalance.toFixed(2) }}</span>
              </div>
            </div>
            <div class="balance-details">
              <div class="detail-item">
                <span class="detail-label">可用余额</span>
                <span class="detail-value">¥{{ userBalance.availableBalance.toFixed(2) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">待结算</span>
                <span class="detail-value">¥{{ userBalance.frozenBalance.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他余额卡片 -->
        <div class="other-balance-cards">
          <div class="balance-card gift-card">
            <div class="card-icon">🎁</div>
            <div class="card-content">
              <span class="card-label">已结算佣金</span>
              <span class="card-amount">¥{{ userBalance.settleBalance.toFixed(2) }}</span>
            </div>
          </div>
          <div class="balance-card points-card">
            <div class="card-icon">⭐</div>
            <div class="card-content">
              <span class="card-label">待结算佣金</span>
              <span class="card-amount">¥{{ userBalance.frozenBalance.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 交易记录区域 -->
    <div class="transaction-section">
      <div class="container">
        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-header">
            <h3 class="section-title">交易记录</h3>
            <div class="date-filter">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                size="large"
                @change="filterByDate" />
            </div>
          </div>

          <div class="filter-tabs">
            <div class="filter-tab" :class="{ active: activeTab === 0 }" @click="setActiveTab(0)">全部</div>
            <div class="filter-tab" :class="{ active: activeTab === 1 }" @click="setActiveTab(1)">收入</div>
            <div class="filter-tab" :class="{ active: activeTab === 2 }" @click="setActiveTab(2)">支出</div>
            <div class="filter-tab" :class="{ active: activeTab === 3 }" @click="setActiveTab(3)">充值</div>
            <div class="filter-tab" :class="{ active: activeTab === 4 }" @click="setActiveTab(4)">提现</div>
            <div class="filter-tab" :class="{ active: activeTab === 5 }" @click="setActiveTab(5)">转账</div>
          </div>
        </div>

        <!-- 交易记录列表 -->
        <div class="transaction-list">
          <div v-for="(transaction, index) in transactions" :key="transaction.id" class="transaction-item">
            <div class="transaction-left">
              <div class="transaction-icon" :class="transaction.event_type">
                <span class="icon">{{ getTransactionIcon(transaction.event_type) }}</span>
              </div>
              <div class="transaction-info">
                <h4 class="transaction-title">{{ transaction.event_type_desc }}</h4>
                <p class="transaction-desc">{{ transaction.event_data }}</p>
                <span class="transaction-time">{{ formatTime(transaction.event_time) }}</span>
              </div>
            </div>
            <div class="transaction-right">
              <div class="transaction-amount" :class="getAmountClass(transaction.event_type)">
                {{ getAmountPrefix(transaction.event_type) }} ¥{{ Math.abs(transaction.change_amount).toFixed(2) }}
              </div>
              <div
                class="transaction-status"
                :class="{ success: transaction.sync_status === 1, pending: transaction.sync_status === 0, fail: transaction.sync_status === 2 }">
                {{ getStatusText(transaction.sync_status) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="transactions.length === 0" class="empty-state">
          <div class="empty-icon">
            <img src="@/assets/images/cart-green.png" alt="暂无记录" class="empty-image" />
          </div>
          <p class="empty-text">暂无交易记录</p>
          <p class="empty-desc">您还没有任何交易记录</p>
        </div>

        <!-- 加载更多 -->
        <div v-if="transactions.length > 0 && hasMore" class="load-more">
          <button class="load-more-btn" @click="loadMore" :loading="loading">
            {{ loading ? '加载中...' : '加载更多' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const userStore = useUserStore()
  const scroll = ref(false)

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 筛选相关
  const activeTab = ref(0)
  const dateRange = ref([])

  // 用户余额信息
  const userBalance = ref({
    totalBalance: 0.0,
    availableBalance: 0.0,
    settleBalance: 0.0,
    frozenBalance: 0.0,
  })

  // 交易记录数据
  const transactions = ref([])

  // 设置激活标签
  const setActiveTab = (tab) => {
    activeTab.value = tab
    fetchData(1)
  }

  // 日期筛选
  const filterByDate = () => {
    // 日期筛选逻辑
    fetchData(1)
  }

  // 获取交易图标
  const getTransactionIcon = (type) => {
    const iconMap = {
      1: '💰',
      2: '🛒',
      3: '💳',
      4: '🏦',
      5: '🏦',
    }
    return iconMap[type] || '💰'
  }

  // 事件类型：1-收入 2-支出 3-充值 4-提现 5-转账(转出) 6-转账(转入)
  // 获取金额样式类
  const getAmountClass = (type) => {
    return [1, 3, 6].includes(type) ? 'positive' : 'negative'
  }

  // 获取金额前缀
  const getAmountPrefix = (type) => {
    return [1, 3, 6].includes(type) ? '+' : '-'
  }

  // 获取状态文本 同步到账户：0未同步 1同步成功 2同步失败
  const getStatusText = (status) => {
    const statusMap = {
      1: '已完成',
      0: '处理中',
      2: '失败',
    }
    return statusMap[status] || '未知'
  }

  // 格式化时间
  const formatTime = (timeStr) => {
    const newDate = new Date(timeStr)
    const now = new Date()
    const diff = now - newDate
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    const year = newDate.getFullYear()
    const month = String(newDate.getMonth() + 1).padStart(2, '0')
    const day = String(newDate.getDate()).padStart(2, '0')

    if (days === 0) {
      return '今天 ' + timeStr.split(' ')[1].substring(0, 5)
    } else if (days === 1) {
      return '昨天 ' + timeStr.split(' ')[1].substring(0, 5)
    } else if (days < 7) {
      return days + '天前'
    } else {
      return `${year}-${month}-${day}`
    }
  }

  // 充值
  const recharge = () => {
    router.push('/recharge')
  }

  // 提现
  const withdraw = () => {
    router.push('/withdraw')
  }

  // 数据分页查询
  const recordCount = ref(0)
  const page = ref(1)
  const limit = ref(6)

  // 是否正在加载
  const loading = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 计算属性 - 是否禁用无限滚动
  const disabled = computed(() => loading.value || !hasMore.value)

  // 分页加载数据
  const fetchData = async (currentPage) => {
    if (loading.value) {
      return
    }
    loading.value = true
    // console.log('分页加载数据', currentPage)
    const startDate = dateRange.value ? dateRange.value[0] : ''
    const endDate = dateRange.value && dateRange.value.length > 1 ? dateRange.value[1] : ''
    apiUser
      .GetBalanceList({
        page: currentPage,
        limit: limit.value,
        event_type: activeTab.value,
        startDate: startDate,
        endDate: endDate,
      })
      .then(async (res) => {
        loading.value = false
        recordCount.value = res.count
        page.value = currentPage
        hasMore.value = currentPage * limit.value < recordCount.value
        if (page.value === 1) {
          transactions.value = res.data
        } else {
          transactions.value = [...transactions.value, ...res.data]
        }
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 加载更多
  const loadMore = () => {
    if (!disabled.value) {
      fetchData(page.value + 1)
    }
  }

  // 查询账户信息
  const loadAccountInfo = () => {
    apiUser.GetAccountInfo().then((res) => {
      if (res.data && res.data.balance) {
        userBalance.value.totalBalance = res.data.balance
        userBalance.value.availableBalance = res.data.balance
        userBalance.value.settleBalance = res.data.settle_commission
        userBalance.value.frozenBalance = res.data.transit_commission
      }
    })
  }

  // 初始化
  onMounted(() => {
    loadAccountInfo()
    fetchData(1)
  })
</script>

<style scoped>
  .balance-page {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
  }

  /* 页面标题区域 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 余额概览区域 */
  .balance-overview {
    padding: 40px 0;
  }

  /* 主要余额卡片 */
  .main-balance-card {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 8px 32px rgba(82, 165, 138, 0.15);
    margin-bottom: 20px;
    position: relative;
    overflow: hidden;
  }

  .main-balance-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #52a58a 0%, #459a7e 100%);
  }

  .balance-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
  }

  .balance-icon .icon-wrapper {
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .wallet-icon {
    font-size: 24px;
  }

  .balance-actions {
    display: flex;
    gap: 12px;
  }

  .action-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 25px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .recharge-btn {
    background: #52a58a;
    color: white;
  }

  .recharge-btn:hover {
    background: #459a7e;
    transform: translateY(-2px);
  }

  .withdraw-btn {
    background: #f8f9fa;
    color: #666;
    border: 1px solid #ddd;
  }

  .withdraw-btn:hover {
    background: #e9ecef;
    border-color: #52a58a;
    color: #52a58a;
  }

  .btn-icon {
    font-size: 16px;
    font-weight: bold;
  }

  .balance-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }

  .total-balance {
    flex: 1;
  }

  .balance-label {
    display: block;
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }

  .balance-amount {
    display: flex;
    align-items: baseline;
    gap: 5px;
  }

  .currency {
    font-size: 20px;
    color: #52a58a;
    font-weight: 500;
  }

  .amount {
    font-size: 36px;
    color: #333;
    font-weight: 700;
  }

  .balance-details {
    display: flex;
    flex-direction: column;
    gap: 8px;
    text-align: right;
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;
  }

  .detail-label {
    font-size: 13px;
    color: #999;
  }

  .detail-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  /* 其他余额卡片 */
  .other-balance-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }

  .balance-card {
    background: white;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    display: flex;
    align-items: center;
    gap: 15px;
    transition: all 0.3s ease;
  }

  .balance-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  }

  .card-icon {
    font-size: 28px;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #f8f9fa;
  }

  .gift-card .card-icon {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  }

  .points-card .card-icon {
    background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
  }

  .card-content {
    flex: 1;
  }

  .card-label {
    display: block;
    font-size: 13px;
    color: #666;
    margin-bottom: 5px;
  }

  .card-amount {
    font-size: 18px;
    color: #333;
    font-weight: 600;
  }

  /* 交易记录区域 */
  .transaction-section {
    padding: 40px 0;
  }

  .filter-section {
    background: white;
    border-radius: 12px;
    padding: 25px;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .section-title {
    font-size: 18px;
    color: #333;
    margin: 0;
    font-weight: 600;
  }

  .date-filter {
    flex-shrink: 0;
  }

  .filter-tabs {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-tab {
    padding: 8px 16px;
    border-radius: 20px;
    background: #f8f9fa;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
    font-weight: 500;
  }

  .filter-tab:hover {
    background: #e9ecef;
    color: #333;
  }

  .filter-tab.active {
    background: #52a58a;
    color: white;
  }

  /* 交易记录列表 */
  .transaction-list {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .transaction-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.3s ease;
  }

  .transaction-item:last-child {
    border-bottom: none;
  }

  .transaction-item:hover {
    background-color: #f8f9fa;
  }

  .transaction-left {
    display: flex;
    align-items: center;
    gap: 15px;
    flex: 1;
  }

  .transaction-icon {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
  }

  .transaction-icon.income {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
  }

  .transaction-icon.expense {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  }

  .transaction-icon.recharge {
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  }

  .transaction-icon.withdraw {
    background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  }

  .transaction-info {
    flex: 1;
  }

  .transaction-title {
    font-size: 16px;
    color: #333;
    margin: 0 0 5px 0;
    font-weight: 500;
  }

  .transaction-desc {
    font-size: 13px;
    color: #666;
    margin: 0 0 5px 0;
    line-height: 1.4;
  }

  .transaction-time {
    font-size: 12px;
    color: #999;
  }

  .transaction-right {
    text-align: right;
    flex-shrink: 0;
  }

  .transaction-amount {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 5px;
  }

  .transaction-amount.positive {
    color: #52a58a;
  }

  .transaction-amount.negative {
    color: #ff4d4f;
  }

  .transaction-status {
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 10px;
    font-weight: 500;
  }

  .transaction-status.completed {
    background: #f6ffed;
    color: #52c41a;
  }

  .transaction-status.pending {
    background: #fff7e6;
    color: #fa8c16;
  }

  .transaction-status.failed {
    background: #fff2f0;
    color: #ff4d4f;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 80px 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .empty-icon {
    margin-bottom: 30px;
  }

  .empty-image {
    width: 120px;
    height: 120px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
    margin-bottom: 0;
  }

  /* 加载更多 */
  .load-more {
    text-align: center;
    margin-top: 30px;
  }

  .load-more-btn {
    background: #f8f9fa;
    border: 1px solid #ddd;
    color: #666;
    padding: 12px 30px;
    border-radius: 25px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .load-more-btn:hover {
    background: #52a58a;
    color: white;
    border-color: #52a58a;
  }

  /* Element Plus 组件样式覆盖 */
  :deep(.el-date-editor) {
    --el-date-editor-width: 240px;
  }

  :deep(.el-date-editor .el-input__inner) {
    border-radius: 8px;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .balance-overview {
      padding: 30px 0;
    }

    .main-balance-card {
      padding: 25px;
    }

    .other-balance-cards {
      gap: 15px;
    }

    .balance-card {
      padding: 20px;
    }

    .transaction-section {
      padding: 30px 0;
    }

    .filter-section {
      padding: 20px;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      padding: 40px 0;
    }

    .page-title {
      font-size: 24px;
    }

    .page-subtitle {
      font-size: 14px;
    }

    .balance-overview {
      padding: 30px 0;
    }

    .container {
      padding: 0 20px;
    }

    .main-balance-card {
      padding: 20px;
    }

    .balance-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 20px;
    }

    .balance-actions {
      width: 100%;
      justify-content: space-between;
    }

    .action-btn {
      flex: 1;
      justify-content: center;
      padding: 12px 20px;
    }

    .balance-content {
      flex-direction: column;
      align-items: flex-start;
      gap: 20px;
    }

    .balance-details {
      width: 100%;
      flex-direction: row;
      justify-content: space-between;
    }

    .detail-item {
      flex-direction: column;
      gap: 5px;
      text-align: center;
    }

    .other-balance-cards {
      grid-template-columns: 1fr;
      gap: 15px;
    }

    .transaction-section {
      padding: 30px 0;
    }

    .filter-section {
      padding: 20px;
    }

    .filter-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }

    .date-filter {
      width: 100%;
    }

    .filter-tabs {
      gap: 10px;
    }

    .filter-tab {
      flex: 1;
      text-align: center;
      min-width: calc(20% - 8px);
    }

    .transaction-item {
      padding: 15px 20px;
    }

    .transaction-left {
      gap: 12px;
    }

    .transaction-icon {
      width: 40px;
      height: 40px;
      font-size: 16px;
    }

    .transaction-title {
      font-size: 15px;
    }

    .transaction-desc {
      font-size: 12px;
    }

    .transaction-amount {
      font-size: 15px;
    }

    .empty-state {
      padding: 60px 15px;
    }

    .empty-image {
      width: 100px;
      height: 100px;
    }

    /* Element Plus 移动端适配 */
    :deep(.el-date-editor) {
      --el-date-editor-width: 100%;
    }
  }

  @media (max-width: 480px) {
    .page-header {
      padding: 30px 0;
    }

    .page-title {
      font-size: 20px;
    }

    .page-subtitle {
      font-size: 13px;
    }

    .container {
      padding: 0 15px;
    }

    .balance-overview {
      padding: 20px 0;
    }

    .main-balance-card {
      padding: 15px;
    }

    .balance-icon .icon-wrapper {
      width: 50px;
      height: 50px;
    }

    .wallet-icon {
      font-size: 20px;
    }

    .action-btn {
      padding: 10px 15px;
      font-size: 13px;
    }

    .amount {
      font-size: 28px;
    }

    .currency {
      font-size: 18px;
    }

    .balance-card {
      padding: 15px;
      gap: 12px;
    }

    .card-icon {
      width: 40px;
      height: 40px;
      font-size: 20px;
    }

    .card-amount {
      font-size: 16px;
    }

    .transaction-section {
      padding: 20px 0;
    }

    .filter-section {
      padding: 15px;
    }

    .section-title {
      font-size: 16px;
    }

    .filter-tabs {
      gap: 8px;
    }

    .filter-tab {
      padding: 6px 12px;
      font-size: 13px;
    }

    .transaction-item {
      padding: 12px 15px;
    }

    .transaction-left {
      gap: 10px;
    }

    .transaction-icon {
      width: 35px;
      height: 35px;
      font-size: 14px;
    }

    .transaction-title {
      font-size: 14px;
    }

    .transaction-desc {
      font-size: 11px;
    }

    .transaction-time {
      font-size: 11px;
    }

    .transaction-amount {
      font-size: 14px;
    }

    .transaction-status {
      font-size: 11px;
      padding: 1px 6px;
    }

    .empty-state {
      padding: 40px 10px;
    }

    .empty-text {
      font-size: 16px;
    }

    .empty-desc {
      font-size: 13px;
    }

    .load-more-btn {
      padding: 10px 25px;
      font-size: 13px;
    }
  }
</style>
